<template>
  <div class="index_page">
    <div id="playerBox"></div>
    <div class="head">
      <el-input size="small" prefix-icon="el-icon-search" v-model="input" placeholder="南京西坝码头"></el-input>
      <h2 v-text="title"></h2>
      <div class="tool_cell">
        <div class="time_cell">{{ date }}  {{ time }}</div>
        <!-- <div class="weather_cell">多云 12℃</div>
        <div class="setting"></div> -->
      </div>
      <div class="tools_box">
        <img src="~@static/img/地球.png" alt="" @click="backAll">
        <!-- <img src="~@static/img/开.png" alt="" v-if="showPage" @click="changePage">
        <img src="~@static/img/关.png" alt="" v-else @click="changePage"> -->
        <el-switch style="display: block" v-model="showPage" active-color="#39CFF0" inactive-color="#7C7C8550"> </el-switch>
      </div>
    </div>
    <div class="menu_cell">
      <div :class="{'active_menu': activePath=='/overView'}" @click="choseMenu('综合态势','/overView', 'P1')">综合态势</div>
      <div :class="{'active_menu': activePath=='/smartView'}" @click="choseMenu('智慧监控','/smartView', 'P2')">智慧监控</div>
      <div :class="{'active_menu': activePath=='/QuickTour'}" @click="choseMenu('一键导览','/QuickTour', 'P3')">一键导览</div> 
    </div>
    <div class="content">
      <router-view/>
    </div>

    <div class="video_Dialog" v-if="showVideoDialog">
      <div class="video_Dialog_content">
        <div class="Dialog_content">
          <i class="el-icon-close" @click="closeVideoDialog"></i> 
          <div class="video_container" id="video-container"></div>
          
          <img class="full_screen_icon" src="~@static/img/全屏.png" alt="" @click="fullScreenBtn()">
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { Config, PixelStreaming } from '@epicgames-ps/lib-pixelstreamingfrontend-ue5.3';
import { Application, PixelStreamingApplicationStyle, UIElementCreationMode } from '@epicgames-ps/lib-pixelstreamingfrontend-ui-ue5.3';

import  EZUIKit from 'ezuikit-js';
export default {
  data() {
    return {
      showVideoDialog: false,
      showPage: true,
      input: "",
      title: "西坝港口生产数字孪生系统",
      date: "",
      time: "",
      activePath: "",  
      player: null,
      accessToken: null,
      expiryDate: null,
      headers: {
        "sign": "d04153093d0f05fad6e4d5dc5c05487bd8f5039d6fe553482d601845345deda7",
        "x-access-token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE3MjcxMzgzNTEsInVzZXJuYW1lIjoiYWRtaW4ifQ.zqpjhBwlBYYLzGC9wcmElKRHJGE4SaKWHC-vNqZhafg"
      },
      tableList: [],
      modelUrl: "", 
    }
  },
  created() {
    window.addEventListener('beforeunload', this.handleBeforeUnload);
  },
  mounted() {
    this.$nextTick(()=>{
      this.getTime();
    }); 
    this.activePath = this.$route.path;

    // 单模型地址模式
    // this.getModel(this.$sysConfig.modelUrl);
    this.getModel("/agencyIpOne");
    
    // 多模型地址模式
    // this.getModelUrl();


    this.$bus.$on("send-Message",(res)=>{
      this.sendMessage(res);
    });
    this.monitoringCamera(); 
    this.initPlayer();  
    this.$bus.$on("play-Video",(res)=>{  
      this.playVideo(res);
    });
  },
  methods: {
    handleBeforeUnload(){
      this.changeMdelUrlStatus(0);
    },
    async getModelUrl(){
      let _this = this;  
      
      let url = `${_this.$sysConfig.getModelUrl}/ueProject/getUEAddress`;  
      _this.$axios.get(url).then(res=>{  
        console.log(res,"getModelUrl-----------------res"); 
        let result = res.data;
        if(result !== ""){ 
          _this.modelUrl = result;  


          var agencyIP = "";
          if(result.includes("36.152.27.182:801")){
            agencyIP = "/agencyIpOne"
          }else if(result.includes("36.152.27.182:802")){
            agencyIP = "/agencyIpTwo"
          } 
          
          _this.getModel(agencyIP);


          // _this.getModel(result);
          _this.changeMdelUrlStatus(1);
        }else{
          _this.$message.warning("暂无空闲节点可用，请关闭目前不需要用的节点的浏览器后，再重试……");
        }
      });
      
    },
    changeMdelUrlStatus(status){
      let _this = this;  
      let url = `${_this.$sysConfig.getModelUrl}/ueProject/updateUEAddressConfig`;   
      let params = {
        address: _this.modelUrl,
        status
      } 
      
      _this.$axios.get(url, {params}).then(res=>{  
        console.log(res,"changeMdelUrlStatus-----------------res");
      });
    }, 
    monitoringCamera(){
      let _this = this;
      let url = `${_this.$sysConfig.baseUrl}/digital/statistics/monitoring_camera`; 
      _this.$axios.get(url, {headers: _this.headers}).then(res=>{   
          let result = res.data.result;      
          _this.tableList = result;   
          
      })
    },

    getCameraDetail(res){
      let _this = this;
      let cameraName = res.split(",")[1];
      if(_this.tableList.length > 0){
        _this.tableList.forEach( item => {
          if(item.monitoringCameraName === cameraName){ 
              _this.showVideoDialog = true;  
              _this.$bus.$emit("play-Video",item.monitoringCameraUrl);
          }
        });
      }
    },

    playVideo(url){
      let _this = this;      
      
      _this.player = new EZUIKit.EZUIKitPlayer({ 
          id: "video-container", // 视频容器ID
          accessToken: _this.accessToken,
          url,  
          width: 0.48 * window.innerWidth, 
          height: 0.6 * window.innerHeight, 
      });
      _this.player.play();
    },

    async initPlayer() {
      let _this = this;
      const token = this.getAccessToken();  
      
      if (!token) { 
        try {
          const response = await this.fetchAccessToken();
          let accessToken = response.data.data.accessToken;
          let expiryDate = new Date(new Date().getTime() + 7 * 24 * 60 * 60 * 1000); // 7 days later
          _this.saveAccessToken(accessToken, expiryDate);
        } catch (error) {
          console.error('Failed to fetch access token:', error);
          return;
        }
      }  
    },

    async fetchAccessToken() {
      const url = "https://open.ys7.com/api/lapp/token/get";
      const data = new FormData();
      data.append('appKey', '536ef90cccf643aaad8686a9bb7a7726');
      data.append('appSecret', '780464ffacc9eef363aa95d17c835be0');

      try {
          const response = await this.$axios.post(url, data); 
          
          return response;
      } catch (error) {
          if (error.response && error.response.status === 401 && error.response.data.code === '10002') {
              // Token 过期，尝试重新获取
              return this.fetchAccessToken();
          }
          throw error;
      }
    },

    getAccessToken() {
      let _this = this;
      const storedToken = localStorage.getItem('accessToken');
      const storedExpiry = localStorage.getItem('expiryDate');
      _this.accessToken = storedToken;
      _this.expiryDate = storedExpiry;
      const now = new Date();

      console.log(new Date(storedExpiry),storedToken,storedExpiry);
      

      if (storedToken && storedExpiry && new Date(storedExpiry) > now) {
          return storedToken;
      }
      return null;
    },

    saveAccessToken(token, expiry) {
      localStorage.setItem('accessToken', token);
      localStorage.setItem('expiryDate', expiry.toISOString());
      this.accessToken = token;
      this.expiryDate = expiry;
    },
    closeVideoDialog(){
      this.player.closeSound();
      this.player.stop();
      this.showVideoDialog = false;
    },
    fullScreenBtn(){
        if(this.player){
            this.player.fullScreen();
        }
    },
    changePage(data){  
      this.showPage = !this.showPage;
    },

    async getModel(modelUrl){ 
      const PixelStreamingApplicationStyles = new PixelStreamingApplicationStyle();
      PixelStreamingApplicationStyles.applyStyleSheet();
  

      // Create a config object创建配置
      const config = new Config({ useUrlParams: true ,
      initialSettings: {
          ss: modelUrl, 
          // ss: "ws://192.168.1.10:801",
          AutoConnect: true,
          StartVideoMuted: true,
          HoveringMouse: true, 
          MatchViewportRes: this.$sysConfig.MatchViewportRes,
      }});


      // Create a Native DOM delegate instance that implements the Delegate interface class
      const stream = new PixelStreaming(config);  
      //设置推流UI
      const application = new Application({
        stream,
        onColorModeChanged: (isLightMode) => PixelStreamingApplicationStyles.setColorMode(isLightMode),
        //左侧设置按钮——关闭
        settingsPanelConfig: {isEnabled:true,visibilityButtonConfig:{creationMode:UIElementCreationMode.Disable}},
        //左侧状态面板——关闭
        statsPanelConfig:{isEnabled : true,visibilityButtonConfig : { creationMode : UIElementCreationMode.Disable }},
        //左侧全屏按钮——关闭
        fullScreenControlsConfig: {creationMode: UIElementCreationMode.Disable,},
        //左下信号强度指示器——关闭
        videoQpIndicatorConfig:{disableIndicator:true},  

        
      });
      this.StreamingApplication = application;
      let playerBox = document.getElementById("playerBox")
      playerBox.appendChild(application.rootElement);

      stream.addResponseEventListener("handle_responses", this.myHandleResponseFunction)
      this.Streaming = stream;
 
    },
    myHandleResponseFunction(response){ 
      // console.log("**********接收到UE消息：",response);   
      let _this = this;  
      if(response.includes("作业")){ 
        _this.$bus.$emit("get-JobDetail",response);
      } 
      if(response.includes("堆垛")){ 
        _this.$bus.$emit("get-stackDetail",response);
      } 
      if(response.includes("摄像头")){ 
        _this.getCameraDetail(response);
      }
    },

    backAll(){
      this.sendMessage("回到起始视角");
    },

    sendMessage(data){
      this.Streaming.emitUIInteraction(data); 
      // console.log(data,"sendMessage******************"); 
      
    },
    getTime(){
      let _this = this;
      setInterval(function () {
        let date = new Date();
        let year = date.getFullYear(); // 年
        let month = date.getMonth() + 1; // 月
        month = month < 10 ? "0" + month : month;
        let day = date.getDate(); // 日
        day = day < 10 ? "0" + day : day;
        _this.date = year + "." + month + "." + day;

        let hour = date.getHours(); // 时
        hour = hour < 10 ? "0" + hour : hour; // 如果只有一位，则前面补零
        let minute = date.getMinutes(); // 分
        minute = minute < 10 ? "0" + minute : minute; // 如果只有一位，则前面补零
        let second = date.getSeconds(); // 秒
        second = second < 10 ? "0" + second : second; // 如果只有一位，则前面补零
        _this.time = `${hour}:${minute}:${second}`
      }, 1000);
    }, 
    choseMenu(data,path,page){  
      this.activePath = path;
      this.$router.push(path);
      this.sendMessage(page); 
    },
  },
  beforeDestroy() { 
    // 组件销毁前移除事件监听器
    window.removeEventListener('beforeunload', this.handleBeforeUnload);
  },
}
</script>

<style lang="scss" scoped> 
@import "@/assets/styles/index.scss";   

.video_Dialog{
  width: 100%;
  height: 100%;
  position: fixed;
  top: 0;
  left: 0;
  background-color: rgba(0,0,0,0.5);
  z-index: 9999; 
  // backdrop-filter: blur(5px);
  .video_Dialog_content{
    position: absolute;
    top: 50%;
    left: 51.2%;
    transform: translate(-50%,-50%); 
    // width: 48vw;
    // height: 70vh;
    background: url("~@static/img/dialog.png") no-repeat 0 0/100% 100%;
    .Dialog_content{
      width: 100%;
      height: 100%; 
      position: relative;
      padding: 2vh 1vw 3vh;
      box-sizing: border-box;
      .el-icon-close{ 
        float: right;
        font-size: 1.2vw;
        color: #fff;
        font-weight: bold; 
        cursor: pointer;
        margin-bottom: 1vh;
      }
      .video_container{
        width: 100%;
        height: calc(100% - 3vh); 
      }
    }
    .full_screen_icon{
      position: absolute;
      bottom: 4vh;
      left: 1.4vw;
      width: 1.2vw;
      height: auto;
      cursor: pointer;
    }
      
  }
}

.tools_box{
  position: absolute;
  top: 9vh;
  right: 2vw;
  display: flex;
  justify-content: center;
  align-items: center;
  img{
    width: 2vw;
    height: auto;
    cursor: pointer;
    margin-right: 0.4vw;
  }
}

.head{
  position: relative;
  z-index: 10;
}

#playerBox{
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0; 
  z-index: 1;
}

 

</style>